#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "../Sock/Socket.hpp"
#include "../Sock/errno.hpp"
#include "../Sock/Logmessage.hpp"

namespace echoServer
{
    using namespace std;
    static const uint16_t gport=8080;
    
    class Server
    {
        uint16_t  port_;
        int listen_fd_;
    public:
        Server(const uint16_t port=gport)
            :listen_fd_(-1),port_(port)
        {}    
        void init()
        {
           
            listen_fd_=Socket::CreateSock();
            Socket::Setsockopt(listen_fd_);
            Socket::Bind(listen_fd_,port_);
            Socket::Listen(listen_fd_);
        }

        void run()
        {
            for(;;)
            {
                std::string clientip;
                uint16_t clientport=0;
                int sock=Socket::Accept(listen_fd_,&clientip,&clientport);
                if(sock<0)
                {
                    logMessage(WARNING,"accept err...");
                    continue;
                }
                logMessage(NORMAL,"accept sock [%d] success...",sock);

                serverIO(sock);
                close(sock);
            }

        }
        ~Server(){}

    private:
        void serverIO(int sock)
        {
            char  buffer[1024];
            while (true)
            {
                ssize_t n=read(sock,buffer,sizeof(buffer)-1);
                if(n>0)
                {
                    buffer[n]=0;
                    string outbuffer=buffer;
                    cout<<"recv from client"<<outbuffer<<endl;
                    write(sock,outbuffer.c_str(),outbuffer.size());
                }
                else if(n==0)
                {
                    logMessage(NORMAL,"client quit and I also quit");
                    break;
                }

            }
            
        }
        
    };
}